package com.jiutong.meipengdai.ui.activitys;

import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.jiutong.meipengdai.R;
import com.jiutong.meipengdai.base.BaseActivity;
import com.jiutong.meipengdai.base.BaseApplicationLike;
import com.jiutong.meipengdai.common.Constants;
import com.jiutong.meipengdai.entity.BaseRespond;
import com.jiutong.meipengdai.entity.IdentifyCodeRespond;
import com.jiutong.meipengdai.entity.LoginOrRegisterRespond;
import com.jiutong.meipengdai.http.model.interfaces.RegisterAndLoginBiz;
import com.jiutong.meipengdai.http.model.requests.CheckPhoneNumRequest;
import com.jiutong.meipengdai.http.present.UserInfoPresent;
import com.jiutong.meipengdai.http.subscribers.ProgressSubscriber;
import com.jiutong.meipengdai.http.subscribers.SubscriberOnNextListener;
import com.jiutong.meipengdai.utils.SpConfig;
import com.jiutong.meipengdai.utils.StringUtil;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by suxi on 2017/5/27.
 */

public class LoginActivity extends BaseActivity implements RegisterAndLoginBiz {
    @Bind(R.id.iv_cancel)
    ImageView ivCancel;
    @Bind(R.id.et_username)
    EditText etUsername;
    @Bind(R.id.et_password)
    EditText etPassword;
    @Bind(R.id.tv_forget_password)
    TextView tvForgetPassword;
    @Bind(R.id.btn_login)
    Button btnLogin;
    @Bind(R.id.tv_register)
    TextView tv_register;
    private UserInfoPresent present;

    @Override
    public int getLayoutResouceId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        super.initView();
        ButterKnife.bind(this);
        present = new UserInfoPresent(this, this);

        if(!TextUtils.isEmpty(SpConfig.getInstance().getString(Constants.USERNAME_STRING))){
            etUsername.setText(SpConfig.getInstance().getString(Constants.USERNAME_STRING));
        }
    }

    @OnClick({R.id.iv_cancel, R.id.btn_login, R.id.tv_register, R.id.tv_forget_password})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_cancel:
                finish();
                break;
            case R.id.btn_login:
                if (!isRightAction())
                    return;
                isPhoneOk();
                break;
            case R.id.tv_register:
                openActivity(RegisterActivity.class);
                break;
            case R.id.tv_forget_password:
                openActivity(PwdFrogetActivity.class);
                break;
        }
    }

    private SubscriberOnNextListener onNextListener;
    private HashMap<String, Object> fieldsMap;
    private ProgressSubscriber progressSubscriber;
    private CheckPhoneNumRequest checkPhoneNumRequest;

    private void isPhoneOk() {
        if(checkPhoneNumRequest == null){
            checkPhoneNumRequest = new CheckPhoneNumRequest();
        }
        onNextListener = new SubscriberOnNextListener<BaseRespond>() {
            @Override
            public void onNext(BaseRespond object) {
                BaseRespond respond = (BaseRespond) object;
                if (respond.getResCode().equals("200")) {
                    present.login();
                } else {
                    toastShortShow(respond.getResDesc());
                }

            }

            @Override
            public void onError(Throwable e) {

            }
        };
        fieldsMap = new HashMap<>();
        fieldsMap.put("phoneNo", getPhoneNum());
        progressSubscriber = new ProgressSubscriber(onNextListener, mContext);
        checkPhoneNumRequest.checkPhoneNum(progressSubscriber, fieldsMap);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    /**
     * 操作是否正确
     *
     * @return
     */
    private boolean isRightAction() {
        if (TextUtils.isEmpty(getPhoneNum())) {
            toastShortShow("请输入手机号码");
            return false;
        }

        if (!StringUtil.isMobileNumber(getPhoneNum())) {
            toastShortShow("手机号码格式有误，请输入正确手机号码");
            return false;
        }

        if (TextUtils.isEmpty(getPassword())) {
            toastShortShow("请输入密码");
            return false;
        }
        return true;
    }

    @Override
    public String getPhoneNum() {
        return etUsername.getText().toString().trim();
    }

    @Override
    public String getPassword() {
        return etPassword.getText().toString().trim();
    }

    @Override
    public String getVerificatCode() {
        return null;
    }

    @Override
    public void onSuccess(Object object) {
//        LoginOrRegisterRespond respond = (LoginOrRegisterRespond) object;
//        SpConfig.getInstance().putString(PayConstants.SESSIONID_STRING, respond.getData().getSessionId());
//        SpConfig.getInstance().putBool(PayConstants.ISAUTH_BOOLEAN, "1".equals(respond.getData().getIdentification()) ? true:false);
//        BaseApplicationLike.getInstance().setUserName(getPhoneNum());
//        finish();
        LoginOrRegisterRespond respond = (LoginOrRegisterRespond) object;
        if (respond.getResCode().equals("200")) {
            SpConfig.getInstance().putString(Constants.SESSIONID_STRING, respond.getData().getSessionId());
            SpConfig.getInstance().putBool(Constants.ISAUTH_BOOLEAN, respond.getData().getIdentification().equals("0") ? false : true);
            SpConfig.getInstance().putString(Constants.REALNAME_STRING, TextUtils.isEmpty(respond.getData().getRealName()) ? "" : respond.getData().getRealName());
            SpConfig.getInstance().putString(Constants.RMAIL_STRING, TextUtils.isEmpty(respond.getData().getEmail()) ? "" : respond.getData().getEmail());
            SpConfig.getInstance().putString(Constants.HEADERIMG_STRING, TextUtils.isEmpty(respond.getData().getHeaderImg()) ? "" : respond.getData().getHeaderImg());
            SpConfig.getInstance().putString(Constants.TEPPHONE_STRING, TextUtils.isEmpty(respond.getData().getTelphone()) ? getPhoneNum() : respond.getData().getTelphone());
            SpConfig.getInstance().putBool(Constants.BANKSTATE_BOOLEAN, respond.getData().getBankNoState().equals("0") ? false : true);
            SpConfig.getInstance().putString(Constants.USERNAME_STRING, getPhoneNum());
            BaseApplicationLike.getInstance().setUserName(getPhoneNum());
            finish();
        } else {
            toastShortShow("用户名或者密码不正确");
        }
    }

    @Override
    public void onError(Throwable e) {
    }

    @Override
    public String getOriPwd() {
        return null;
    }

    @Override
    public String getNewPwd() {
        return null;
    }

    @Override
    public String getRelName() {
        return null;
    }

    @Override
    public String getIdCard() {
        return null;
    }

    @Override
    public String getEmail() {
        return null;
    }

    @Override
    public String getNewPhone() {
        return null;
    }

    @Override
    public String getCardNumber() {
        return null;
    }

    @Override
    public void onVerCodeGetSuccess(IdentifyCodeRespond subjects) {

    }

}
